package com.real.operationalcontrols;


import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.ToastUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.king.base.baseurlmanager.util.BaseUrlUtil;
import com.kongzue.tabbar.Tab;
import com.kongzue.tabbar.TabBarView;
import com.kongzue.tabbar.interfaces.OnTabChangeListener;
import com.mob.pushsdk.MobPush;
import com.mob.pushsdk.MobPushCallback;
import com.next.easynavigation.view.CustomViewPager;
import com.real.operationalcontrols.fragment.FragmentCompany;
import com.real.operationalcontrols.fragment.FragmentTask;
import com.real.operationalcontrols.基类.BaseActivity;
import com.real.operationalcontrols.实体类.LocationBean;
import com.real.operationalcontrols.登陆.SetingActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.vp)
    CustomViewPager vp;
    @BindView(R.id.bar)
    TabBarView bar;
    @BindView(R.id.bar_back_btn)
    ImageView barBackBtn;
    @BindView(R.id.bar_title)
    TextView barTitle;
    @BindView(R.id.bar_check_btn)
    TextView barCheckBtn;
    List<Tab> tabs = new ArrayList<>();
    List<Fragment> fragmentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void getData() {
        //获取服务器地址域名
        String address = BaseUrlUtil.getBseUrlInfo(this).getName();
        barBackBtn.setVisibility(View.GONE);
        barCheckBtn.setVisibility(View.VISIBLE);
        barTitle.setText(address);
        barCheckBtn.setText("设置");
        //开启定位
        initLocation();
        initPush();
        fragmentList.add(new FragmentTask());
        fragmentList.add(new FragmentCompany());
        tabs.add(new Tab(this, "任务列表", R.mipmap.bar_baojing));
        tabs.add(new Tab(this, "企业列表", R.mipmap.bar_zhandian));
        bar.setTab(tabs);
        MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
        vp.setCanScroll(false);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(fragmentList.size() - 1);
        bar.setOnTabChangeListener(new OnTabChangeListener() {
            @Override
            public void onTabChanged(View v, int index) {
                vp.setCurrentItem(index, true);
            }
        });
        bar.setNormalFocusIndex(0);
        vp.setCurrentItem(0, true);
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(3000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        //启动后台定位，第一个参数为通知栏ID，建议整个APP使用一个
        mLocationClient.enableBackgroundLocation(2001, buildNotification());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //获取当前城市来获取天气
                String shen = amapLocation.getProvince();//省
                String city = amapLocation.getCity();//城市信息
                String code = amapLocation.getAdCode();//编码
                double lon = amapLocation.getLongitude();//经度
                double lat = amapLocation.getLatitude();//纬度
                LiveEventBus.get("location").post(new LocationBean(200, lon, lat));
                //Log.i("gaogao", "当前定位经度为-----" + lon + "当前定位纬度为-----" + lat);
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
                LiveEventBus.get("location").post(new LocationBean(404, 0, 0));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            //关闭后台定位，参数为true时会移除通知栏，为false时不会移除通知栏，但是可以手动移除
            mLocationClient.disableBackgroundLocation(true);
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    }

    private void initPush() {
        //获取注册id
        MobPush.getRegistrationId(new MobPushCallback<String>() {
            @Override
            public void onCallback(String data) {
                Log.i("MobPushLog", "注册的推送id是---" + data);
            }
        });

        if (Build.VERSION.SDK_INT >= 21) {
            MobPush.setNotifyIcon(R.mipmap.logo);
        } else {
            MobPush.setNotifyIcon(R.mipmap.logo);
        }
    }

    @OnClick(R.id.bar_check_btn)
    public void onViewClicked() {
        startActivity(new Intent(this, SetingActivity.class));
    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return fragmentList.get(i);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }

    //记录当前时间
    long thisTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - thisTime < 2000) {
                System.exit(0);
            } else {
                ToastUtils.showShort("再按一次退出程序");
                thisTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    boolean isCreateChannel = false;

    @SuppressLint("NewApi")
    private Notification buildNotification() {

        Notification.Builder builder = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.mipmap.logo)
                .setContentTitle("运维管控")
                .setContentText("正在运行")
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }
}
